package com.boyou.sytzc.core.appctx

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Process
import com.boyou.sytzc.data.MyObjectBox

import com.boyou.sytzc.utils.common.DeviceNoManager

import io.objectbox.BoxStore
import io.objectbox.DebugFlags
import io.objectbox.android.AndroidObjectBrowser

/**
 * Created by Mrper on 16.5.14.
 * App Application对象
 */
class AppApplication : Application() {

    /**
     * 获取BoxStore对象
     */
    lateinit var boxStore: BoxStore
        private set

    override fun onCreate() {
        super.onCreate()
        instance = this //获取应用实例
        boxStore = MyObjectBox.builder().androidContext(this)
            .debugFlags(
                DebugFlags.LOG_QUERIES.or(DebugFlags.LOG_QUERY_PARAMETERS)
                    .or(DebugFlags.LOG_TRANSACTIONS_READ).or(DebugFlags.LOG_TRANSACTIONS_WRITE)
            )
            .build()
        if (getProcessName(this, Process.myPid()) == "com.boyou.sytzc") {
            dnm = DeviceNoManager.getInstance(this)
            if (com.boyou.sytzc.BuildConfig.DEBUG) {
                AndroidObjectBrowser(boxStore).start(this)
            }
        }
    }

    companion object {

        lateinit var instance: AppApplication
            private set

        @SuppressLint("StaticFieldLeak")
        private var dnm: DeviceNoManager? = null

        /** 设备号对象 **/
        @JvmStatic
        val deviceNoManager: DeviceNoManager
            get() = dnm!!

        /**
         * 获取进程名称
         *
         * @param cxt 上下文对象
         * @param pid 进程的PID
         */
        fun getProcessName(cxt: Context, pid: Int): String {
            val am = cxt.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val processes = am.runningAppProcesses
            if (processes != null && processes.size > 0) {
                for (procInfo in processes) {
                    if (procInfo.pid == pid) {
                        return procInfo.processName
                    }
                }
            }
            return ""
        }
    }

}
